package com.raising.modules.sys.service;

import com.raising.StaticParam;
import com.raising.framework.service.CrudService;
import com.raising.modules.sys.dao.OrganizationDao;
import com.raising.modules.sys.entity.Organization;
import com.raising.utils.JStringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 组织机构服务
 *
 * @author gaoy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrganizationService extends CrudService<OrganizationDao, Organization> {

    /**
     * 查询是否存在下级节点
     * @param id
     * @return
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public int findNext(String id){
        return dao.findNext(id);
    }

    /**
     * 根据单位标识id查询机构当前下属单位最大的编号no
     * @author GaoYuan
     * @datetime 2018/1/24 下午5:19
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public String getSubMaxNoById(String id){
        return dao.getSubMaxNoById(id);
    }
    /**
     * 执行数据上下级清洗操作（自动拼凑上下级）
     * @author GaoYuan
     * @datetime 2018/1/24 下午7:01
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTree(){
//        dao.updateTree();
        Organization organization_query = new Organization();
        organization_query.setStatus(StaticParam.VALID_STRING);
        organization_query.setOrderBy(" a.id asc ");
        List<Organization> organizationList = dao.getList(organization_query);
        if(organizationList.size()>0){
            Organization organization = organizationList.get(0);
            /**递归处理*/
            this.updateByNo(organization.getId(),organization.getNo());
        }
    }
    /**
     * 更新用户no
     * @author GaoYuan
     * @datetime 2018/2/3 下午3:55
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateByNo(String id,String no){
        List<Organization> organizationList = dao.getNextNode(no,no.length()+2);
        if(organizationList==null || organizationList.size() == 0){
            return;
        }
        for(Organization organ:organizationList){
            dao.updateParentId(organ.getId(),id);
            updateByNo(organ.getId(),organ.getNo());
        }
    }
    /**
     * 更新单位头像
     * @author GaoYuan
     * @datetime 2018/2/3 下午3:55
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateHeadImg(Organization organization){
        return dao.updateHeadImg(organization);
    }

    /**
     * 获取最顶级单位数据
     * @author GaoYuan
     * @datetime 2018/2/3 下午3:54
     */
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public Organization getGroupOrgId(){
        return dao.getGroupOrgId();
    }
}
